package com.boot.controller;

import com.boot.entity.*;
import com.boot.repository.*;

import com.boot.vo.BaseMessage;
import com.boot.vo.Course;
import com.boot.vo.MessageHandler;

import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.transaction.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseInfoRepository courseInfoRepository;
    @Autowired
    private BuildingRepository buildingRepository;
    @Autowired
    private ClassroomRepository classroomRepository;
    @Autowired
    private TimeAndPlaceRepository timeAndPlaceRepository;
    @Autowired
    private SchoolRepository schoolRepository;
    @Autowired
    private MajorRepository majorRepository;
    @Autowired
    private TeaInfoRepository teaInfoRepository;
    @Autowired
    private TermRepository termRepository;

    @Autowired
    private CourseOpenRepository courseOpenRepository;

    //admin添加/修改课程(add=true，edit=false)
    @RequestMapping("adminCourseInfo")
    @ResponseBody
    public BaseMessage<?> addCourseInfo(@RequestParam Boolean addOrEdit, @RequestBody CourseInfo courseInfo) {
        Boolean b = courseInfoRepository.existsByCourseSerialNumber(courseInfo.getCourseSerialNumber());
        if (addOrEdit == true)
            if (b == true)
                return MessageHandler.createFailedVo("课程已存在,不可重复添加课程");
        if (addOrEdit == false)
            if (b == false)
                return MessageHandler.createFailedVo("课程序列号不存在,请先添加课程信息");
        //校验格式
        String s = checkAddFormat(courseInfo);
        if (s.startsWith("0"))
            return MessageHandler.createFailedVo(s.substring(1, s.length()));
        courseInfo.setFlag(true);
        //courseInfo.setStatus(0); 不用status了
        courseInfo.setCourseEnrollment(0);
        if (courseInfo.getCourseCapacity() == null)
            courseInfo.setCourseCapacity(100);
        courseInfoRepository.save(courseInfo);
        return MessageHandler.createSuccessVo("课程添加/修改成功");
    }

    //管理员添加修改时间信息
    @RequestMapping("adminTAP")
    @ResponseBody
    public BaseMessage<?> addCourseTAP(@RequestBody List<TimeAndPlace> timeAndPlaces) {
        for (TimeAndPlace timeAndPlace : timeAndPlaces) {
            Boolean b = courseInfoRepository.existsByCourseSerialNumber(timeAndPlace.getCourseSerialNumber());
            if (b == false)
                return MessageHandler.createFailedVo("课程序列号不存在");
            //校验时间地点安排冲突+教室容量冲突
            Boolean tapRepeated = checkTAPRepeated(timeAndPlace);
            if (tapRepeated == false)
                return MessageHandler.createFailedVo("课程时间地点安排冲突");
            //校验教室课程安排冲突
            if (checkTeaRepeated(timeAndPlace) == false)
                return MessageHandler.createFailedVo("教师课程安排冲突");
            timeAndPlaceRepository.save(timeAndPlace);
        }
        return MessageHandler.createSuccessVo("课程时间地点添加成功");
    }


    //tea申请新增课程，修改课程
    @PostMapping("teaCourseInfo")
    @ResponseBody
    public BaseMessage<?> teaCourseInfo(@RequestParam Boolean addOrEdit, @RequestBody CourseInfo courseInfo) {
        Boolean b = courseInfoRepository.existsByCourseSerialNumber(courseInfo.getCourseSerialNumber());
        if (addOrEdit == true)
            if (b == true)
                return MessageHandler.createFailedVo("课程已存在,不可重复添加课程");
        if (addOrEdit == false)
            if (b == false)
                return MessageHandler.createFailedVo("课程序列号不存在,请先添加课程信息");
        //校验格式
        String s = checkAddFormat(courseInfo);
        if (s.startsWith("0"))
            return MessageHandler.createFailedVo(s.substring(1, s.length()));
        courseInfo.setFlag(false);
        //courseInfo.setStatus(0); 不用status了
        courseInfo.setCourseEnrollment(0);
        courseInfoRepository.save(courseInfo);
        return MessageHandler.createSuccessVo("课程添加/修改成功");
    }


    //删除课程
    @Transactional
    @RequestMapping("del")
    @ResponseBody
    public BaseMessage<?> delCourse(@RequestBody Integer courseSerialNum) {
        CourseInfo courseInfo = courseInfoRepository.findByCourseSerialNumber(courseSerialNum);
        if (courseInfo.getCourseEnrollment() > 0)
            return MessageHandler.createFailedVo("此课程有学生选课，不可删除");
        courseInfoRepository.deleteByCourseSerialNumber(courseSerialNum);
        timeAndPlaceRepository.deleteAllByCourseSerialNumber(courseSerialNum);
        return MessageHandler.createSuccessVo("课程删除成功");
    }


    //管理员：根据学年学期、上课时间(星期几、第几节）、上课地点找课。第几节课就是一个数字，比如说周一的2-5是高数，我查找周一的第4节课就能显示高数，查第1节就啥也没有
    @GetMapping("/admin/findByTermAndTimeAndPlace")
    public BaseMessage<?> findByTermAndTimeAndPlace(Integer termid, Integer weekday, Integer jieshu, String classroom) {
        List<TimeAndPlace> taps = timeAndPlaceRepository.findAllByWeekdayAndClassroom(weekday, classroom);
        CourseInfo courseInfo = new CourseInfo();
        for (TimeAndPlace tap : taps) {
            //找所有星期几、节数、教室符合的
            if (jieshu <= tap.getEnd() && jieshu >= tap.getStart()) {
                courseInfo = courseInfoRepository.findByCourseSerialNumber(tap.getCourseSerialNumber());
                //再判断是不是这个学期的
                if (courseInfo.getTermId() == termid)
                    return MessageHandler.createSuccessVo(courseInfo, "查找成功");
            }
        }
        return MessageHandler.createFailedVo("该学期该时间地点没有课程");
    }

    //管理员：根据课程编号模糊搜索
    @GetMapping("admin/findByCourseNum")
    public BaseMessage<?> adminFindByCourseNum(Integer cnum) {
        List<CourseInfo> courseInfoList = courseInfoRepository.findAllByCourseNumberLike(cnum);
        if (courseInfoList.size() == 0 || null == courseInfoList)
            return MessageHandler.createFailedVo("该课程编号不存在");
        return MessageHandler.createSuccessVo(courseInfoList, "");
    }

    //管理员：根据课程老师名字模糊搜索
    @GetMapping("admin/findByTeaName")
    public BaseMessage<?> adminFindByCourseNum(String teaname) {
        //名字模糊搜索工号
        List<TeaInfo> teaInfos = teaInfoRepository.findAllByNameLike(teaname);
        if (teaInfos.size() == 0 || null == teaInfos) {
            return MessageHandler.createFailedVo("该教师不存在");
        }
        List<CourseInfo> tempList = new ArrayList<>();
        for (TeaInfo teaInfo : teaInfos) {
            tempList.addAll(courseInfoRepository.findAllByWorkNumber(teaInfo.getWorkNumber()));
        }
        return MessageHandler.createSuccessVo(tempList, "");
    }

    //管理员：根据课程名字模糊搜索
    @GetMapping("admin/findByCourseName")
    public BaseMessage<?> adminFindByCourseName(String cname) {
        List<CourseInfo> courseInfoList = courseInfoRepository.findAllByCourseNameLike(cname);
        if (courseInfoList.size() == 0 || null == courseInfoList)
            return MessageHandler.createFailedVo("该课程名字不存在");
        return MessageHandler.createSuccessVo(courseInfoList, "");
    }

    //根据课程编号获取上课时间
    @GetMapping("findTAPByCourseId")
    public BaseMessage<?> findTAPByCouseId(Integer courseId) {
        List<TimeAndPlace> timeAndPlaces = timeAndPlaceRepository.findAll();
        return MessageHandler.createSuccessVo(timeAndPlaces, "课程的所有时间地点返回成功");

    }


    @GetMapping("allCourseInfo")
    public BaseMessage<?> allCourseInfo() {
        List<CourseInfo> courseInfoList = courseInfoRepository.findAll();
        return MessageHandler.createSuccessVo(courseInfoList, "所有课程返回成功");
    }

    //搜索课程（根据名字找课程）
    @GetMapping("courseList")
    public BaseMessage<?> courseList(@RequestParam String name) {
        List<CourseInfo> courseInfoList;
        if (StringUtils.isBlank(name))
            courseInfoList = courseInfoRepository.findAllByFlag(true);
        else
            courseInfoList = courseInfoRepository.findAllByFlagAndCourseName(true, name);
        return MessageHandler.createSuccessVo(courseInfoList, "查询成功");
    }

    //根据教室找课程表
    @GetMapping("schedule")
    public BaseMessage<?> schedule(@RequestParam Integer buildingId, @RequestParam Integer classroomId) {
        Building building = buildingRepository.findByBuildingId(buildingId);
        Classroom classroom = classroomRepository.findByClassroomId(classroomId);
        List<TimeAndPlace> timeAndPlaces = timeAndPlaceRepository.findAllByBuildingAndClassroom(building.getBuildingName(), classroom.getClassroomName());
        List<Course> courseList = new ArrayList<>();
        for (TimeAndPlace tap : timeAndPlaces) {
            CourseInfo courseInfo = courseInfoRepository.findByCourseSerialNumber(tap.getCourseSerialNumber());
            Course course = courseInfoAndTAPToCourse(courseInfo, tap);
            courseList.add(course);
        }
        return MessageHandler.createSuccessVo(courseList, "");
    }


    /**
     * 选课开关权限
     *
     * @return
     */
    @GetMapping("/selCoursePermission")
    public String selCoursePermission(@RequestBody CourseOpen courseOpen) {
        Integer termid = judgeTermId();
        courseOpen.setTermId(termid);
        courseOpenRepository.save(courseOpen);
        return "redirect:/selCourse/round1kick";

    }

//    //csv导入
//    @PostMapping(value = "/importCsv")
//    public BaseMessage<?> upload(@RequestParam("file") MultipartFile file) {
//        try {
//            //上传内容不能为空
//            if (file.isEmpty()) {
//                return MessageHandler.createFailedVo("文件内无数据！");
//            }
//            File newFile = CSVUtils.uploadFile(file);
//            List<List<String>> userRoleLists = CSVUtils.readCSV(newFile.getPath(), 16);
//            ArrayList<String> names = new ArrayList<>();
//            userRoleLists.forEach(e -> {
//                Course course = new Course();
//                course.setCourseNumber(Integer.parseInt(e.get(0)));
//                course.setCourseName(e.get(1));
//                course.setSchoolId(Integer.parseInt(e.get(2)));
//                course.setCourseCredit(Double.parseDouble(e.get(3)));
//                course.setCoursePeriod(Double.parseDouble(e.get(4)));
//                course.setWorkNumber(e.get(5));
//                course.setCourseDesc(e.get(6));
//                course.setCourseCapacity(Integer.parseInt(e.get(7)));
//                course.setMajorId(Integer.parseInt(e.get(8)));
//                course.setFlag(Boolean.parseBoolean(e.get(9)));
//                course.setStatus(Boolean.parseBoolean(e.get(10)));
//                course.setStart(Integer.parseInt(e.get(11)));
//                course.setEnd(Integer.parseInt(e.get(12)));
//                course.setWeekday(Integer.parseInt(e.get(13)));
//                course.setBuilding(e.get(14));
//                course.setClassroom(e.get(15));
//               //TODO:没改完
//                String check = check(course);
//                if (check.equals("0")) {
//                    courseInfoRepository.save(course);
//                } else {
//                    names.add(course.getCourseName());
//                }
//            });
//            newFile.delete();
//            return MessageHandler.createSuccessVo("操作成功"+( names.size() > 0 ?"沒有添加成功的課程名稱有："+ names.stream().collect(Collectors.joining(",")) : ""));
//        } catch (Exception e) {
//            e.printStackTrace();
//            return MessageHandler.createFailedVo(e.getMessage());
//        }
//    }


    // 审核 flase 是不通过 true 是 通过
    @PostMapping("/flag/{num}/{flag}")
    public BaseMessage<?> flag(@PathVariable Boolean flag, @PathVariable Integer num) {
        CourseInfo courseInfo = courseInfoRepository.findByCourseSerialNumber(num);
        courseInfo.setFlag(flag);
        courseInfoRepository.save(courseInfo);
        return MessageHandler.createSuccessVo("操作成功");
    }


    public String checkAddFormat(CourseInfo courseInfo) {
        Boolean existsBySchoolId = schoolRepository.existsBySchoolId(courseInfo.getSchoolId());
        if (existsBySchoolId == false)
            return "0学院不存在";
        if (courseInfo.getCourseCredit() <= 0 || courseInfo.getCoursePeriod() <= 0)
            return "0学时学分必须大于0";
        Boolean existsByWorkNumber = teaInfoRepository.existsByWorkNumber(courseInfo.getWorkNumber());
        if (existsByWorkNumber == false)
            return "0教师工号不存在";
//        Boolean existsByMajorId=majorRepository.existsByMajorId(courseInfo.getMajorId());
//        if(existsByMajorId==false)
//            return "0专业不存在";
        if (courseInfo.getCourseCapacity() < 0)
            return "0课程容量必须大于0";
        return "1添加成功！！！！！！";
    }


    //检查老师时间冲突
    public Boolean checkTeaRepeated(TimeAndPlace newtap) {
        CourseInfo courseInfo = courseInfoRepository.findByCourseSerialNumber(newtap.getCourseSerialNumber());
        //根据老师找课程序列号
        List<Integer> serialNumList = new ArrayList<>();
        List<CourseInfo> courseInfoList = courseInfoRepository.findAllByWorkNumber(courseInfo.getWorkNumber());
        for (CourseInfo c : courseInfoList)
            serialNumList.add(c.getCourseSerialNumber());
        //根据序列号和星期几找时间冲突
        for (Integer i : serialNumList) {
            List<TimeAndPlace> timeAndPlaces = timeAndPlaceRepository.findAllByWeekdayAndAndCourseSerialNumber(newtap.getWeekday(), i);
            for (TimeAndPlace tap : timeAndPlaces) {
                if (newtap.getStart() <= tap.getStart() && newtap.getEnd() >= tap.getStart())
                    return false;
                if (newtap.getStart() <= tap.getEnd() && newtap.getEnd() >= tap.getEnd())
                    return false;
            }
        }
        return true;
    }

    //检查时间地点冲突+教室容量冲突
    public Boolean checkTAPRepeated(TimeAndPlace newtap) {
        Classroom classroom = classroomRepository.findByClassroomName(newtap.getClassroom());
        CourseInfo courseInfo = courseInfoRepository.findByCourseSerialNumber(newtap.getCourseSerialNumber());
        if (courseInfo.getCourseCapacity() > classroom.getCapacity())
            return false;
        List<TimeAndPlace> timeAndPlaces = timeAndPlaceRepository.findAllByWeekdayAndClassroom(newtap.getWeekday(), newtap.getClassroom());
        for (TimeAndPlace tap : timeAndPlaces) {
            if (newtap.getStart() <= tap.getStart() && newtap.getEnd() >= tap.getStart())
                return false;
            if (newtap.getStart() <= tap.getEnd() && newtap.getEnd() >= tap.getEnd())
                return false;
        }
        return true;
    }


    //    public CourseInfo toInfo(Course c){
//        CourseInfo courseInfo=new CourseInfo();
//        courseInfo.setCourseSerialNumber(c.getCourseSerialNumber());    courseInfo.setCourseNumber(c.getCourseNumber());
//        courseInfo.setCourseName(c.getCourseName());                    courseInfo.setSchoolId(c.getSchoolId());
//        courseInfo.setCourseCredit(c.getCourseCredit());                courseInfo.setCoursePeriod(c.getCoursePeriod());
//        courseInfo.setWorkNumber(c.getWorkNumber());                    courseInfo.setCourseDesc(c.getCourseDesc());
//        courseInfo.setCourseEnrollment(c.getCourseEnrollment());        courseInfo.setMajorId(c.getMajorId());
//        courseInfo.setCourseCapacity(c.getCourseCapacity());
//        courseInfo.setKxzy(c.getKxzy());                                courseInfo.setTermId(c.getTermId());
//        courseInfo.setFlag(true);   //审核状态默认为true
//        courseInfo.setStatus(0);    //选课状态默认为false
//        return courseInfo;
//    }
//
//    public TimeAndPlace toTAP(Course c) {
//        TimeAndPlace timeAndPlace = new TimeAndPlace();
//        timeAndPlace.setCourseSerialNumber(c.getCourseSerialNumber());
//        timeAndPlace.setBuilding(c.getBuilding());
//        timeAndPlace.setClassroom(c.getClassroom());
//        timeAndPlace.setStart(c.getStart());
//        timeAndPlace.setEnd(c.getEnd());
//        timeAndPlace.setWeekday(c.getWeekday());
//        return timeAndPlace;
//    }
//
    //courseInfo和tap到course
    public Course courseInfoAndTAPToCourse(CourseInfo courseInfo, TimeAndPlace timeAndPlace) {
        Course c = new Course();
        c.setCourseSerialNumber(courseInfo.getCourseSerialNumber());
        c.setCourseNumber(courseInfo.getCourseNumber());
        c.setCourseName(courseInfo.getCourseName());
        c.setSchoolId(courseInfo.getSchoolId());
        c.setCourseCredit(courseInfo.getCourseCredit());
        c.setCoursePeriod(courseInfo.getCoursePeriod());
        c.setWorkNumber(courseInfo.getWorkNumber());
        c.setCourseDesc(courseInfo.getCourseDesc());
        c.setCourseEnrollment(courseInfo.getCourseEnrollment());
        c.setMajorId(courseInfo.getMajorId());
        c.setCourseCapacity(courseInfo.getCourseCapacity());
        c.setKxzy(courseInfo.getKxzy());
        c.setTermId(courseInfo.getTermId());
        c.setStatus(0);
        c.setFlag(true);   //审核状态默认为true,选课状态默认为0
        c.setStart(timeAndPlace.getStart());
        c.setEnd(timeAndPlace.getEnd());
        c.setBuilding(timeAndPlace.getBuilding());
        c.setClassroom(timeAndPlace.getClassroom());
        c.setWeekday(timeAndPlace.getWeekday());
        return c;
    }

    public Integer judgeTermId() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);
        Integer year = cal.get(Calendar.YEAR);
        Integer term;   //1/2学期
        if (month >= 2 && month <= 6)
            term = 2;
        else if (month >= 9 || month == 1)
            term = 1;
        else
            term = 3;
        Term term1 = termRepository.findByYearAndTerm(year, term);
        return term1.getTermid();
    }

}
